package com.blog.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blog.admin.mapper.PermissionMapper;
import com.blog.admin.pojo.auth.Permission;
import com.blog.admin.pojo.auth.User;
import com.blog.admin.service.PermissionService;
import com.blog.admin.utils.UserUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public List<Permission> selectAll() {
		List<Permission> resourcesList = permissionMapper.selectAll();
		return resourcesList;
	}

	/**
	 * 根据用户查询菜单
	 * 
	 * @param user
	 * @return 菜单列表
	 */
	@Override
	public List<Permission> selectMenusByUser(User user) {
		List<Permission> menus = new LinkedList<Permission>();
		// 管理员显示所有菜单信息 一级菜单
		if (UserUtils.isAdmin()) {
			menus = permissionMapper.getAllMenu();
		} else {
			menus = permissionMapper.getMenusByUserId(user.getId());
		}
		List<Permission> resultMenus = new LinkedList<Permission>();
		//遍历一级菜单获取二级菜单
		for (Permission permission : menus) {
			List<Permission> childMenus = permissionMapper.getAllMenus(permission.getId());
			permission.setChildren(childMenus);
			resultMenus.add(permission);
		}
		return resultMenus;
	}

	@Override
	public boolean deletePermission(String id) {
		Integer a = permissionMapper.deletePermission(Integer.valueOf(id));
		if (a == 1) {
			return true;
		}
		return false;
	}

	@Override
	public Permission getPermissionById(Integer id) {
		return permissionMapper.getPermissionById(id);
	}

	@Override
	public Integer update(Permission permission) {
		return permissionMapper.update(permission);
	}

	@Override
	public Integer insert(Permission permission) {
		return permissionMapper.insert(permission);
	}
}
